<?php
// +----------------------------------------------------------------------
// | YFCMF [ WE CAN DO IT MORE SIMPLE]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2020 http://yfcmf.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: rainfer <rainfer520@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\model\visit;

class VisitLog extends \think\Model
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'visitTime';

    public function getIpAttr($value)
    {
        return long2ip($value);
    }

    /**
     * 获取访问log列表
     *
     * @param $visitor
     * @param $ip
     * @param $uri
     * @param $visitTime
     * @param $startTime
     * @param $endTime
     * @param $order
     * @param $page
     * @param $psize
     *
     * @return array
     * @throws
     */
    public static function getLists($visitor = '-1', $ip = '', $uri = '', $visitTime = 'all', $startTime = '', $endTime = '', $order = 'id desc', $page = 1, $psize = 10)
    {
        $where = [];
        if ($visitor !== '-1') {
            $where[] = ['visitor', '=', $visitor];
        }
        if ($ip) {
            $where[] = ['ip', '=', ip2long($ip)];
        }
        if ($uri) {
            $where[] = ['uri', 'like', '%' . $uri . '%'];
        }
        // 创建时间
        $whereTime = [];
        if ($visitTime == 'custom') {
            $whereTime[] = ['visitTime', 'between', [$startTime, $endTime]];
        } else {
            $whereTime = where_between_time($visitTime, 'visitTime');
        }
        return self::where($where)->where($whereTime)->order($order)->page($page, $psize)->select();
    }

    /**
     * 获取访问log数量
     *
     * @param $visitor
     * @param $ip
     * @param $uri
     * @param $visitTime
     * @param $startTime
     * @param $endTime
     *
     * @return int
     * @throws
     */
    public static function getTotal($visitor = '-1', $ip = '', $uri = '', $visitTime = 'all', $startTime = '', $endTime = '')
    {
        $where = [];
        if ($visitor !== '-1') {
            $where[] = ['visitor', '=', $visitor];
        }
        if ($ip) {
            $where[] = ['ip', '=', ip2long($ip)];
        }
        if ($uri) {
            $where[] = ['uri', 'like', '%' . $uri . '%'];
        }
        // 创建时间
        $whereTime = [];
        if ($visitTime == 'custom') {
            $whereTime[] = ['visitTime', 'between', [$startTime, $endTime]];
        } else {
            $whereTime = where_between_time($visitTime, 'visitTime');
        }
        return self::where($where)->where($whereTime)->count();
    }
}
